//
//  PNNetworkTool.swift
//  新浪微博
//
//  Created by MBP on 16/5/14.
//  Copyright © 2016年 MBP. All rights reserved.
//

import UIKit
import AFNetworking

//网络请求方式的枚举
enum PNRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class PNNetworkTool: AFHTTPSessionManager {
    // 应用程序 标识
    let AppKey = "1453346095"
    let AppSecret = "ad767826ce33b2e708ae9d911d57aadc"
    let redirectUri = "http://www.baidu.com"
    
    //network 单例
    static let sharedTools: PNNetworkTool = {
       let tools = PNNetworkTool(baseURL: nil)
        
        // 设置 AFN 的网络 `请求` 超时
        tools.requestSerializer.timeoutInterval = 15
        
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        // 将 JSON 中的 NULL 值过滤，有些第三方框架在做字典转模型时，如果遇到 NULL 值会崩溃！
        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        
        // 启动连接状态监听 - 通过通知中心发布的
        tools.reachabilityManager.startMonitoring()

        return tools
    }()
    
    deinit {
        // 停止连接状态监听
        reachabilityManager.stopMonitoring()
    }
    
    /// 判断当前网络是否能够连接
    var reachable: Bool {
        return reachabilityManager.reachable
    }
    
    //封装AFN网络请求方法
    func request(method: PNRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished:(result: [String: AnyObject]?) -> ()) {
        //成功回调
        let success = { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            
            if let result = responseObject as? [String: AnyObject] {
                finished(result: result)
            }else {
                print("数据格式错误")
                finished(result: nil)
            }
        }
        //失败回调
        let failure = {(task: NSURLSessionDataTask?, error: NSError) -> Void in
            
            print("网络请求错误\(error)")
            finished(result: nil)
        }
        
        
        if method == .GET {
            //get请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            //post请求
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }


}
